package com.xhl.noval.svc.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.xhl.noval.api.core.entity.ApiResult;
import com.xhl.noval.api.service.NovelService;
import groovy.util.logging.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Objects;

/**
 * @author xionghl
 * @Description: 小说爬虫-serviceImpl层
 * @date 2022/4/16 15:31
 */
@RestController
@Service
@Slf4j
public class NovelServiceImpl implements NovelService {

    @Override
    public ApiResult<String> resolveSingleNovel(String url) throws IOException {
        long t1 = System.currentTimeMillis();
        this.resolveSingleNovelContent(url);
        return ApiResult.success(url + "\n" +"解析完毕，总耗时：" + (System.currentTimeMillis()-t1)/1000.0 + "s");
    }

    private void resolveSingleNovelContent(String url) throws IOException {

        Document document = Jsoup.connect(url).get();
        //小说名
        String novelName = "未知";
        Elements nameElements = document.getElementsByClass("bookTitle");
        if(ObjectUtil.isNotEmpty(nameElements)){
            novelName = Objects.requireNonNull(nameElements.first()).html();
        }
        //作者
        String author = "佚名";
        Elements booktagElements = document.getElementsByClass("booktag");
        if(ObjectUtil.isNotEmpty(booktagElements)){
            Elements tagList = Objects.requireNonNull(booktagElements.first()).select("a");
            if(ObjectUtil.isNotEmpty(tagList)){
                author = Objects.requireNonNull(tagList.first()).html();
            }
        }
        String fileName = "C:\\Users\\xhl\\Desktop\\" + novelName + "【作者：" + author +"】.txt";
        //获取章节列表
        Elements chapterElementList = document.select("div#list-chapterAll a");

        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true)));
            if (ObjectUtil.isNotEmpty(chapterElementList)) {
                for(Element chapterElement : chapterElementList){
                    String chapterUrl = getHref(chapterElement);
                    //章节名
                    String chapterName = chapterElement.html();
                    //解析域名
                    String context = url.substring(0,url.indexOf(".com")+4);
                    //写文件
                    out.write(chapterName+"\r\n");
                    out.write(resolveChapterContent(context + "/" + chapterUrl)+"\r");
                    System.out.println("【" + chapterName + "】解析完毕！");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert out != null;
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 解析章节内容
     * @param url 章节url
     */
    private String resolveChapterContent(String url) throws IOException {
        Document document = Jsoup.connect(url).get();
        Elements htmlContent = document.select("div#htmlContent");
        StringBuilder chapterContent = new StringBuilder();
        if(ObjectUtil.isNotEmpty(htmlContent)){
            Element content = htmlContent.first();
            //字符转义
            assert content != null;
            chapterContent.append(content.html().replace("<br>","").replace("&nbsp;",""));
            return chapterContent.toString();
        }
        return "";
    }
    /**
     * 获取a标签href属性
     *
     * @param a 标签
     * @return 返回值
     */
    private static String getHref(Element a) {
        String href = Objects.nonNull(a) && StrUtil.isNotBlank(a.attr("href")) ? a.attr("href").trim() : "";
        return href.replace("&amp;", "&");
    }

    @Override
    public String resolveWebsiteNovel() {
        return "hey~~~~~";
    }
}
